package interfaces

import (
	"fmt"
	"github.com/gin-gonic/gin"
	"net/http"
	"ruoyi/application"
	"ruoyi/domain/entity/response"
	"ruoyi/domain/entity/system"
	"ruoyi/utils"
	"strconv"
)

type LoginService struct {
	login   application.UserAppInterface
	captcha application.ConfigAppInterface
	log     application.LogAppInterface
	menu    application.MenuAppInterface
	role    application.RoleAppInterface
	dept    application.DeptAppInterface
}

//LoginService constructor
func NewLoginService(login application.UserAppInterface, captcha application.ConfigAppInterface,
	log application.LogAppInterface, menu application.MenuAppInterface,
	role application.RoleAppInterface, dept application.DeptAppInterface) *LoginService {
	return &LoginService{
		login:   login,
		captcha: captcha,
		log:     log,
		menu:    menu,
		role:    role,
		dept:    dept,
	}
}

// Login
// @Tags     Base
// @Summary  用户登录
// @Produce   application/json
// @Param    data  body      model.LoginParam                                             true  "用户名, 密码, 验证码"
// @Success  200   {object}  response.Response{response.SysCaptchaResponse,msg=string}  "返回包括用户信息,token,过期时间"
// @Router   /login [post]
func (f *LoginService) LoginHandler(context *gin.Context) {
	var param system.LoginParam
	if err := context.ShouldBind(&param); err != nil {
		f.log.LoginInfoAdd(context, param, "登录失败，参数为空", false)
		context.JSON(http.StatusOK, response.ReturnFailMsg("参数不能为空"))
		return
	} else {
		var captchaEnabled = f.captcha.SelectCaptchaEnabled()
		if captchaEnabled {
			isVerify := utils.VerifyCaptcha(param.Uuid, param.Code)
			if isVerify {
				isExist := f.login.IsExistUser(param.UserName)
				if isExist {
					f.login.FindUser(param, context)
				} else {
					f.log.LoginInfoAdd(context, param, "登录失败，用户不存在", false)
					context.JSON(http.StatusOK, gin.H{
						"msg":  "用户不存在",
						"code": http.StatusInternalServerError,
					})
				}
			} else {
				f.log.LoginInfoAdd(context, param, "登录失败，验证码错误", false)
				context.JSON(http.StatusOK, gin.H{
					"msg":  "请输入正确的验证码",
					"code": http.StatusInternalServerError,
				})
			}
		} else {
			isExist := f.login.IsExistUser(param.UserName)
			if isExist {
				f.login.FindUser(param, context)
			} else {
				f.log.LoginInfoAdd(context, param, "登录失败，用户不存在", false)
				context.JSON(http.StatusOK, gin.H{
					"msg":  "用户不存在",
					"code": http.StatusInternalServerError,
				})
			}
		}
	}
}

func (f *LoginService) GetRoutersHandler(context *gin.Context) {
	userId, _ := context.Get("userId")

	f.login.FindUserById(userId)

	//if user == nil {
	//	context.JSON(http.StatusOK, gin.H{
	//		"msg":  "未找到用户",
	//		"code": http.StatusInternalServerError,
	//	})
	//	return
	//}

	menu := f.menu.SelectMenuTreeByUserId(utils.GetInterfaceToInt(userId))
	var data = f.menu.BuildMenus(menu)
	context.JSON(http.StatusOK, gin.H{
		"msg":  "操作成功",
		"code": http.StatusOK,
		"data": data,
	})
}

func (f *LoginService) LogoutHandler(context *gin.Context) {
	userId, _ := context.Get("userId")
	var user = f.login.FindUserById(userId)
	fmt.Println(user)
	// 开始删除缓存
	context.JSON(http.StatusOK, gin.H{
		"msg":  "退出成功",
		"code": http.StatusOK,
	})
}

func (f *LoginService) GetInfoHandler(context *gin.Context) {
	userId, _ := context.Get("userId")
	fmt.Println(userId)
	var user = f.login.FindUserById(userId)
	roles := f.role.GetRolePermission(user)
	permissions := f.role.GetMenuPermission(user)
	dept := f.dept.GetDeptInfo(strconv.Itoa(user.DeptId))
	context.JSON(http.StatusOK, gin.H{
		"msg":  "获取成功",
		"code": http.StatusOK,
		"user": gin.H{
			"userName":    user.UserName,
			"NickName":    user.NickName,
			"phonenumber": user.PhoneNumber,
			"email":       user.Email,
			"avatar":      user.Avatar,
			"sex":         user.Sex,
			"createTime":  user.CreateTime,
			"dept":        dept,
		},
		"roles":       roles,
		"permissions": permissions,
	})
}
